<template>
  <div class="ueditor-wrapper" :style="{ width: typeof width === 'number' ? `${width}px` : width }">
    <div :id="editorId" class="ueditor-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick, toRefs } from 'vue';

interface Props {
  modelValue?: string;
  height?: number;
  width?: string | number;
  placeholder?: string;
  readonly?: boolean;
  disabled?: boolean;
  config?: Record<string, any>;
}

interface Emits {
  (e: 'update:modelValue', value: string): void;
  (e: 'ready', editor: any): void;
  (e: 'change', value: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  height: 400,
  width: '100%',
  placeholder: '请输入内容...',
  readonly: false,
  config: () => ({}),
});

// 解构props以便在模板中使用
const { width } = toRefs(props);

const emit = defineEmits<Emits>();

// 生成唯一的编辑器ID
const editorId = ref(`ueditor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`);

// 编辑器实例
let editorInstance: any = null;

// 内容双向绑定
const content = computed({
  get: () => props.modelValue,
  set: (value: string) => {
    emit('update:modelValue', value);
    emit('change', value);
  }
});

// 加载UEditor脚本
const loadUEditorScript = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if ((window as any).UE) {
      resolve();
      return;
    }

    // 加载UEditor配置文件
    const configScript = document.createElement('script');
    configScript.src = '/UEditor/ueditor.config.js';
    configScript.onload = () => {
      // 加载UEditor主文件
      const mainScript = document.createElement('script');
      mainScript.src = '/UEditor/ueditor.all.js';
      mainScript.onload = () => resolve();
      mainScript.onerror = () => reject(new Error('Failed to load UEditor main script'));
      document.head.appendChild(mainScript);
    };
    configScript.onerror = () => reject(new Error('Failed to load UEditor config script'));
    document.head.appendChild(configScript);
  });
};

// 初始化编辑器
const initEditor = async () => {
  try {
    await loadUEditorScript();
    await nextTick();
    
    // 确保DOM元素存在
    const container = document.getElementById(editorId.value);
    if (!container) {
      console.error('UEditor container not found:', editorId.value);
      return;
    }
    
    if (editorInstance) {
      editorInstance.destroy();
      editorInstance = null;
    }

    const UE = (window as any).UE;
    if (!UE) {
      throw new Error('UEditor not loaded');
    }

    // 延迟创建编辑器，确保DOM完全准备好
    setTimeout(() => {
      try {
        editorInstance = UE.getEditor(editorId.value, myConfig.value);
        
        if (editorInstance) {
          editorInstance.ready(() => {
            // 设置初始内容
            if (props.modelValue) {
              editorInstance.setContent(props.modelValue);
            }
            
            // 监听内容变化
            editorInstance.addListener('contentChange', () => {
              const newContent = editorInstance.getContent();
              emit('update:modelValue', newContent);
              emit('change', newContent);
            });
            
            // 设置编辑器状态
            if (props.disabled) {
              editorInstance.setDisabled();
            }
            
            emit('ready', editorInstance);
          });
        }
      } catch (innerError: any) {
        console.error('Failed to create UEditor instance:', innerError);
      }
    }, 100);
    
  } catch (error: any) {
    console.error('Failed to initialize UEditor:', error);
  }
};

// UEditor配置
const myConfig = computed(() => {
  const defaultConfig = {
    // UEditor 资源文件的存放路径
    UEDITOR_HOME_URL: '/UEditor/',
    // 服务器统一请求接口路径
    serverUrl: '/api/ueditor/controller',
    // 编辑器初始化结束后,编辑区域是否是只读的
    readonly: props.readonly,
    // 编辑器层级的基数
    zIndex: 999,
    // 编辑器初始内容
    initialContent: '',
    // 初始化编辑器宽度
    initialFrameWidth: typeof props.width === 'number' ? props.width : props.width,
    // 初始化编辑器高度
    initialFrameHeight: props.height,
    // 编辑器不自动被内容撑高
    autoHeightEnabled: false,
    // 工具栏上的所有的功能按钮和下拉框
    toolbars: [[
      'fullscreen', 'source', '|', 'undo', 'redo', '|',
      'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
      'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
      'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
      'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
      'directionalityltr', 'directionalityrtl', 'indent', '|',
      'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
      'touppercase', 'tolowercase', '|',
      'link', 'unlink', 'anchor', '|',
      'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
      'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
      'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
      'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
      'print', 'preview', 'searchreplace', 'drafts', 'help'
    ]],
    // 当鼠标放在工具栏上时显示的tooltip提示
    labelMap: {
      'anchor': '锚点',
      'undo': '撤销',
      'redo': '重做',
      'bold': '加粗',
      'indent': '首行缩进',
      'snapscreen': '截图',
      'italic': '斜体',
      'underline': '下划线',
      'strikethrough': '删除线',
      'subscript': '下标',
      'fontborder': '字符边框',
      'superscript': '上标',
      'formatmatch': '格式刷',
      'source': '源代码',
      'blockquote': '引用',
      'pasteplain': '纯文本粘贴模式',
      'selectall': '全选',
      'print': '打印',
      'preview': '预览',
      'horizontal': '分隔线',
      'removeformat': '清除格式',
      'time': '时间',
      'date': '日期',
      'unlink': '取消链接',
      'insertrow': '前插入行',
      'insertcol': '前插入列',
      'mergeright': '右合并单元格',
      'mergedown': '下合并单元格',
      'deleterow': '删除行',
      'deletecol': '删除列',
      'splittorows': '拆分成行',
      'splittocols': '拆分成列',
      'splittocells': '完全拆分单元格',
      'deletecaption': '删除表格标题',
      'inserttitle': '插入标题',
      'mergecells': '合并多个单元格',
      'deletetable': '删除表格',
      'cleardoc': '清空文档',
      'insertparagraphbeforetable': '表格前插入行',
      'insertcode': '代码语言',
      'fontfamily': '字体',
      'fontsize': '字号',
      'paragraph': '段落格式',
      'simpleupload': '单图上传',
      'insertimage': '多图上传',
      'edittable': '表格属性',
      'edittd': '单元格属性',
      'link': '超链接',
      'emotion': '表情',
      'spechars': '特殊字符',
      'searchreplace': '查询替换',
      'map': '百度地图',
      'gmap': '谷歌地图',
      'insertvideo': '视频',
      'help': '帮助',
      'justifyleft': '居左对齐',
      'justifyright': '居右对齐',
      'justifycenter': '居中对齐',
      'justifyjustify': '两端对齐',
      'forecolor': '字体颜色',
      'backcolor': '背景色',
      'insertorderedlist': '有序列表',
      'insertunorderedlist': '无序列表',
      'fullscreen': '全屏',
      'directionalityltr': '从左向右输入',
      'directionalityrtl': '从右向左输入',
      'rowspacingtop': '段前距',
      'rowspacingbottom': '段后距',
      'pagebreak': '分页',
      'insertframe': '插入Iframe',
      'imagenone': '默认',
      'imageleft': '左浮动',
      'imageright': '右浮动',
      'attachment': '附件',
      'imagecenter': '居中',
      'wordimage': 'word图片',
      'lineheight': '行间距',
      'edittip': '编辑提示',
      'customstyle': '自定义标题',
      'autotypeset': '自动排版',
      'webapp': '百度应用',
      'touppercase': '字母大写',
      'tolowercase': '字母小写',
      'background': '背景',
      'template': '模板',
      'scrawl': '涂鸦',
      'music': '音乐',
      'inserttable': '插入表格',
      'drafts': '从草稿箱加载',
      'charts': '图表'
    },
    // 语言配置
    lang: 'zh-cn',
    // 主题配置
    theme: 'default',
    // placeholder
    placeholder: props.placeholder,
    // 是否开启元素路径
    elementPathEnabled: true,
    // 是否开启字数统计
    wordCount: true,
    // 允许的最大字符数
    maximumWords: 10000,
    // 自定义样式
    iframeCssUrl: '',
    // 粘贴时是否自动处理
    retainOnlyLabelPasted: false,
    // 是否保持toolbar的位置不变
    autoFloatEnabled: true
  };
  
  // 合并用户自定义配置
  return { ...defaultConfig, ...props.config };
});

// 组件挂载时初始化编辑器
onMounted(() => {
  initEditor();
});

// 组件卸载时销毁编辑器
onUnmounted(() => {
  if (editorInstance) {
    editorInstance.destroy();
    editorInstance = null;
  }
});

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (editorInstance && editorInstance.getContent() !== newVal) {
    editorInstance.setContent(newVal || '');
  }
});

// 监听disabled属性变化
watch(() => props.disabled, (newVal) => {
  if (editorInstance) {
    if (newVal) {
      editorInstance.setDisabled();
    } else {
      editorInstance.setEnabled();
    }
  }
});
</script>

<script lang="ts">
export default {
  name: 'UEditor'
};
</script>

<style scoped>
.ueditor-wrapper {
  width: 100%;
}

.ueditor-container {
  width: 100%;
  min-height: 400px;
}
</style>

<style>
/* 确保编辑器在弹窗中正常显示 */
.edui-default {
  z-index: 9999 !important;
}

.edui-popup {
  z-index: 10000 !important;
}

.edui-dialog {
  z-index: 10001 !important;
}

/* 工具栏样式优化 */
.edui-toolbar {
  border: 1px solid #ddd;
  background: #f9f9f9;
}

/* 编辑区域样式 */
.edui-editor-iframeholder {
  border: 1px solid #ddd;
  border-top: none;
}

/* 底部状态栏 */
.edui-editor-bottomContainer {
  border: 1px solid #ddd;
  border-top: none;
  background: #f9f9f9;
}
</style>